<?php
 /**
   * This program is free software; you can redistribute it and/or
   * modify it under the terms of the GNU General Public License
   * as published by the Free Software Foundation; either version 2
   * of the License, or any later version.
   *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with this program; if not, write to the Free Software
   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
   *
   * ----------------------------------------------------------------------
   * NimWiki - designer centric wiki
   *
   * @author Nicolas Myers <myers.nicolas@gmail.com>
   * @copyright 2007 Nicolas Myers
   * @version 0.9.0
   * @link
   * ----------------------------------------------------------------------
   * CORE.PHP
   *
   * main functions
   * ----------------------------------------------------------------------
   */
   
   
   /**
    * Templating function, outputs the content (last function to run)
    * @param  array   $contentArray  vars availables in template
    * @param  string  $tpl           php template file
    */
    function outputPage($contentArray, $tpl)
    {
        extract($contentArray, EXTR_OVERWRITE);
        include($tpl);
    }

   /**
    * Retrieves the requested page and outputs it
    * @param  string  $pagename  page to display
    * @param  string  $message   message to display (error, confirmation...)
    */
    function showPage($pagename, $message = "")
    {
        global $cfg;
        //prevents from seeing archive file
        if(!(strpos($pagename, '.') === false))
            $pagename = substr($pagename, 0, strpos($pagename, '.'));
        //tests if the page exists
        $pagename = pageExists($pagename) ? $pagename : $cfg['page_default'];
        setTemplate($pagename);
        $output['pagename']     = $pagename;
        $output['lastmodified'] = date('H:i:s F d Y', filemtime(getFilename($pagename)));
        $output['message']      = $message;
        $output['cfg']          = $cfg;
        outputPage($output, $cfg['tpl_dir'] . $cfg['tpl_show']);
    }

   /**
    * Edits the current page, if it's new : creates an empty one
    * @param  string  $pagename  page to edit
    */
    function editPage($pagename)
    {
        global $cfg;
        $output['versions']  = getVersions($pagename);
        $output['content']   = pageExists($pagename) ? file_get_contents(getFilename($pagename)) : '';
        $output['pagename']  = $pagename;
        $output['cfg']       = $cfg;
        outputPage($output, $cfg['tpl_dir'] . $cfg['tpl_edit']);
    }

   /**
    * Saves the current page
    * @param  string  $pagename  page to save
    */
    function savePage($pagename)
    {
        $pagename = str_replace('/', '#', $pagename);
        $data = rtrim($_POST['content']);
        // removes the archive suffix (date + time)
        if(!(strpos($pagename, '.') === false))$pagename = substr($pagename, 0, strpos($pagename, '.'));
        // archive the old file i.e. add a date to the end of the filename
        $filename = getFilename($pagename);
        if (file_exists($filename)) {
            $date = date('Y-m-d-H-i', filemtime($filename));
            @rename($filename, str_replace('.dat', ".$date.dat", $filename));
        }
        // now write the data into the page file
        $handle = fopen($filename, 'w');
        if (!fwrite($handle, $data)) {
            die("Error writing Data into $filename");
        }
        fclose($handle);
    }
    
   /**
    * Deletes the current page -> moves data files in the trash dir
    * @param  string  $pagename  page to delete
    */
    function deletePage($pagename)
    {
        global $cfg;
        $pagename = str_replace('/', '#', $pagename);
        foreach ($cfg['lang_array'] as $lang) {
            $handle = opendir($cfg['data_dir'].$lang);
            while ($newfile = readdir($handle)) {
                if (strpos($newfile,$pagename.'.')!==false) 
                    echo $newfile."<br>";
            }
        }

    }
    

   /**
    * Returns the data filename matching the pagename.
    * @param   string  $pagename 
    * @return  string  full filename (including path) 
    */
    function getFilename($pagename)
    {
        global $cfg;
        $pagename = str_replace('/', '#', $pagename);
        return $cfg['data_dir'] . $cfg['lang'] . '/' . $pagename . $cfg['data_ext'];
    }

   /**
    * Tests if the data file exists
    * @param   string  $pagename 
    * @return  bool    true if it exists, false otherwise 
    */
    function pageExists($pagename)
    {
        global $cfg;
        $pagename = str_replace('/', '#', $pagename);
        return file_exists($cfg['data_dir'] . $cfg['lang'] . '/' . $pagename . $cfg['data_ext']);
    }

   /**
    * Reads the uri to get the request pagename
    * @return string  the filtered pagename 
    */
    function getPage()
    {
        global $cfg;
        $pagename = empty($_GET[$cfg['wiki_get']]) ? $cfg['page_default'] : $_GET[$cfg['wiki_get']];
        $pagename = str_replace('/', '#', $pagename);
        return $pagename;
    }

   /**
    * Returns the page's categories
    * e.g:  "/music/pop/agreat-album" => array("root","music","pop"); )
    * @param   string  $pagename 
    * @return  array   the categories' list  
    */    
    function getCategory($pagename)
    {
        global $cfg;
        $catArr = explode('/', 'root/' . substr($pagename, 0, strrpos($pagename, '/')));
        if($catArr[1] == '')array_pop($catArr);
        return $catArr;
    }

   /**
    * Returns the current language code
    * @return  string  language code ( e.g:  "en", "fr" )
    */ 
    function getLang()
    {
        global $cfg;
        if(empty($_SESSION['lang']))
            $_SESSION['lang'] = $cfg['lang_default'];
        if(!empty($_GET['lang']) and in_array($_GET['lang'], $cfg['lang_array']))
            $_SESSION['lang'] = $_GET['lang'];
        return $_SESSION['lang'];
    }

   /**
    * Returns the pagename's versions (including the current one)
    * @param   string  $pagename
    * @return  array   list of page's version ("mypage.2007-02-04-20-10", "mypage.2007-02-03-18-28")
    */ 
    function getVersions($pagename)
    {
        global $cfg;
        $handle = opendir($cfg['data_dir'] . $cfg['lang']);
        $pagename = basePagename($pagename);
        $i = 0;
        $allpages = array();
        while ($newfile = readdir($handle)) {
            if (strpos($newfile, $pagename) !== false) {
                //
                $name = basename($newfile, $cfg['data_ext']);
                $date = substr(strstr($name, '.'), 1);
                if ($date != '') {
                    $allpages[$i]['name'] = $name;
                    $allpages[$i]['date'] = $date;
                    $i++;
                }
            }
        }
        @rsort($allpages);
        array_unshift($allpages, array('name' => $pagename, 'date' => 'Dernière version'));
        return $allpages;
    }

   /**
    * Returns the pagename without version suffix
    * @param   string  $pagename 
    * @return  string  filtered pagename
    */ 
    function basePagename($pagename)
    {
        $pagename = str_replace('/', '#', $pagename);
        if(!(strpos($pagename, '.') === false))
            return substr($pagename, 0, strpos($pagename, '.'));
        else
            return $pagename;
    }

   /**
    * Returns the pagename without version suffix
    * @param   string  $pagename 
    * @return  string  filtered pagename
    */
    function setTemplate($pagename)
    {
        global $cfg;
        $pagename = str_replace('#', '/', $pagename);
        foreach ($cfg['tpl_routing'] as $rule => $tpl_file) {
            if (preg_match($rule, $pagename)) {
                $cfg['tpl_show'] = $tpl_file;
                break;
            }
        }
        foreach ($cfg['css_routing'] as $rule => $css_file) {
            if (preg_match($rule, $pagename)) {
                $cfg['css_show'] = $css_file;
                break;
            }
        }
    }

   /**
    * Checks the POST values for logging infos
    * Starts and sets sessions value 
    * @return  bool  true if user is logged, false otherwise
    */
    function logging()
    {
        global $cfg, $usr;
        session_start();
        if(!isset($_SESSION['logged']))
            $_SESSION['logged'] = false;
        if(!isset($_SESSION['username']))
            $_SESSION['username'] = 'default';
        $username = @$_REQUEST['username'];
        $password = @$_REQUEST['password'];
        if (isset($_REQUEST['password'])) {
            foreach ($usr as $_username => $_userinfo) {
                if ($username == $_username) {
                    if ($password == $_userinfo["password"]) {
                        $_SESSION['logged'] = true;
                        $_SESSION['username'] = $username;
                    }
                }
            }
        } else if (isset($_GET["logout"])) {
            $_SESSION['logged'] = false;
            $_SESSION['username'] = 'default';
        }
        return $_SESSION['logged'];
    }

   /**
    * Checks if the action request is authorized for the current user
    * @param   string  $action   action code (read,write...)
    * @param   string  $pagename 
    * @return  bool    true if authorized, false otherwise
    */
    function isAuthorized($action, $pagename)
    {
        global $cfg, $usr;
        $authorized = false;
        if (isset($usr[$_SESSION['username']][$action])) {
            $authorizedAction     = is_string($usr[$_SESSION['username']][$action]) ? preg_match($usr[$_SESSION['username']][$action], $pagename) : $usr[$_SESSION['username']][$action];
            $authorizedCantAction = isset($usr[$_SESSION['username']]['cant'.$action]) ? preg_match($usr[$_SESSION['username']]['cant'.$action], $pagename) : false;
            return $authorizedAction and !($authorizedCantAction);
        } else {
            return false;
        }
    }

?>
